<template>
  <div id='commodity-manage-list'>
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item"><span class="search-label">输入搜索：</span><Input placeholder="商品名称/条码/编码"
                 v-model='searchObj.skuName'></Input></Col>
          <Col style="display: flex; align-items: center;"
               class="search-item">
          <span class="search-label">商品分类：</span>
          <!-- <Select v-model="searchObj.classify" style="width:200px" @on-change="seleted">
              <OptionGroup :label="ele.categoryName" v-for="(ele, idx) in classifyList" :key='idx'>
                <Option v-for="item in ele.subCategoryList" :value="item.categoryId" :key="item.categoryId">{{ item.categoryName }}</Option>
              </OptionGroup>
            </Select> -->
          <vueTreeselectChoice :width="200"
                               v-model="searchObj.classify"
                               :disable-branch-nodes="true"
                               @input="seleted"
                               :options="classifyList"
                               permissionCode='1'></vueTreeselectChoice>
          </Col>
          <Col class="search-item">
          <span class="search-label">所属类型：</span>
          <Select v-model="searchObj.type"
                  @on-change="seleted"
                  style="width:180px"
                  placeholder='请选择'>
            <Option v-for="item in typeList"
                    :value="item.typeCode"
                    :key="item.typeCode">{{ item.typeName }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="seleted">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item"><Button class="search-btn"
                  type="primary"
                  style="margin-right:8px"
                  v-if="hasPermission(['moms:product:productcreate'])"
                  @click="skipAdd">新增商品</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe
           class="table-list"
           :columns="columns"
           :data="tableData"
           @on-sort-change="sortTable"
           :loading="loading"
           :height="tableHeight">
      <template slot-scope="{ row,index }"
                slot="order">
        <span>{{index + 1}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="thumbnail">
        <div><img :src="row.thumbnail?row.thumbnail:defaultUrl"
               style="width: 90px;height: 60px;display: block;margin: 15px 0;"></div>
      </template>
      <template slot-scope="{ row }"
                slot="classify">
        <span>{{row.parentCategoryName+'/'+row.categoryName}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="goodsKind">
        <span>{{(row.goodsKindList[0]||{}).typeName}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <i class="iconsys icondetail"
           title="查看"
           v-if="hasPermission(['moms:product:productdetail'])"
           @click='skipDetail(row)'></i>
        <i class="iconsys iconedit"
           title="编辑"
           v-if="hasPermission(['moms:product:productupdate'])&&row.goodsStatus!==3"
           @click='skipEdit(row)'></i>
        <i class="iconsys iconrizhi"
           title="日志"
           v-if="hasPermission(['moms:product:productlog'])"
           @click='skipLog(row)'></i>
        <i class="iconsys icondongjie"
           title="冻结商品"
           v-if="hasPermission(['moms:product:productdelete'])"
           @click='freeze(row)'></i>
        <!-- <Poptip confirm
                title="确认复制该商品信息吗？"
                transfer
                v-if="hasPermission(['moms:product:productcopy'])"
                style="text-align:left"> -->
        <i class="iconsys iconfuzhi"
           title="复制商品"
           @click="sureCover(row)"></i>
        <!-- </Poptip> -->
      </template>
    </Table>
    <Row type='flex'
         justify="end"
         style='padding: 20px'>
      <Col>
      <Page :total="pageObj.total"
            :page-size='pageObj.pageSize'
            :current='pageObj.pageIndex'
            :page-size-opts='[20,50,100,200]'
            show-total
            show-sizer
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <Modal v-model="modalShow"
           width="480"
           title="冻结商品"
           :closable='false'>
      <div style="padding: 0 15px">当商品存在有效库存时，无法进行冻结操作；商品冻结确认冻结后，商品信息将停止使用</div>
      <div slot="footer">
        <Button style="width:78px;margin-right:10px"
                @click='cancel'>考虑一下</Button>
        <Button type="primary"
                style="width:78px"
                @click='sureFreeze'>确认冻结</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { shopCategoryList, goodsList, kindList, freezeGoods } from '@/api/goods/index'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
export default {
  name: 'commodity_list',
  components: { vueTreeselectChoice },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    }),
    tableHeight () {
      let height = this.tableData.length > 6 ? 580 : 0
      return height
    }
  },
  data () {
    return {
      defaultUrl: require('@/assets/images/default.png'),
      loading: false,
      modalShow: false,
      searchName: '',
      classifyList: [],
      typeCode: '',
      typeList: [],
      searchObj: {
        skuName: '',
        classify: null,
        type: ''
      },
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      tableData: [],
      columns: [
        {
          title: '排序',
          slot: 'order'
        },
        {
          title: '商品编码',
          key: 'skuId',
          width: 120,
          sortable: 'custom'
        },
        {
          title: '商品主图',
          slot: 'thumbnail'
        },
        {
          title: '商品名称',
          key: 'skuName'
        },
        {
          title: '条码',
          key: 'barcode'
        },
        {
          title: '商品分类',
          slot: 'classify'
        },
        {
          title: '所属类型',
          slot: 'goodsKind'
        },
        {
          title: '制单人',
          key: 'creatorName'
        }
      ],
      clickRow: {}
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.name !== 'commodity_list') {
        vm.loading = true
        vm.tableData = []
        let parmas = {
          merchantId: vm.$store.state.user.merchantId,
          offset: (vm.pageObj.pageIndex - 1) * vm.pageObj.pageSize,
          limit: vm.pageObj.pageSize,
          keyword: vm.searchObj.skuName,
          categoryId: vm.searchObj.classify,
          goodsKind: vm.searchObj.type,
          goodsStatus: 1
        }
        if (!vm.searchObj.type) {
          delete parmas.goodsKind
        }
        if (vm.classifyList.length > 0) {
          if (vm.typeList.length === 0) {
            vm.$Message.error(`你没有相关权限`)
          } else {
            if (vm.typeCode) {
              goodsList({
                ...parmas,
                goodsKind: vm.typeCode
              }).then(res => {
                vm.loading = false
                if (res.data.status === 200) {
                  vm.tableData = res.data.data.goods || []
                  vm.pageObj.total = res.data.data.total || 0
                }
              })
            } else {
              goodsList({
                ...parmas
              }).then(res => {
                vm.loading = false
                if (res.data.status === 200) {
                  vm.tableData = res.data.data.goods || []
                  vm.pageObj.total = res.data.data.total || 0
                }
              })
            }
          }
        }
      }
    })
  },
  mounted () {
    this.getCate()
    this.getkindList()
    if (this.hasPermission(['moms:product:productdetail', 'moms:product:productupdate', 'moms:product:productcopy', 'moms:product:productdelete', 'moms:product:productlog'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 250
      })
    }
  },
  methods: {
    seleted () {
      this.pageObj.pageIndex = 1
      if (this.typeList.length > 0) {
        this.getGoodsList()
      } else {
        this.$Message.error(`你没有相关权限`)
      }
    },
    getGoodsList () {
      this.loading = true
      this.tableData = []
      let parmas = {
        merchantId: this.$store.state.user.merchantId,
        offset: (this.pageObj.pageIndex - 1) * this.pageObj.pageSize,
        limit: this.pageObj.pageSize,
        keyword: this.searchObj.skuName,
        categoryId: this.searchObj.classify,
        goodsKind: this.searchObj.type,
        goodsStatus: 1
      }
      if (!this.searchObj.type) {
        delete parmas.goodsKind
      }
      if (this.typeCode) {
        goodsList({
          ...parmas,
          goodsKind: this.typeCode
        }).then(res => {
          this.loading = false
          if (res.data.status === 200) {
            this.tableData = res.data.data.goods || []
            this.pageObj.total = res.data.data.total || 0
          }
        })
      } else {
        goodsList({
          ...parmas
        }).then(res => {
          this.loading = false
          if (res.data.status === 200) {
            this.tableData = res.data.data.goods || []
            this.pageObj.total = res.data.data.total || 0
          }
        })
      }
    },
    // 获取所属分类
    getkindList () {
      kindList({
        merchantId: this.$store.state.user.merchantId,
        level: 1
      }).then(res => {
        if (res.data.status === 200) {
          this.typeList = res.data.data || []
          if (this.typeList.length === 1) {
            this.typeCode = this.typeList[0].typeCode
            this.getGoodsList()
          } else if (this.typeList.length === 0) {
            this.$Message.error(`你没有相关权限`)
          } else {
            this.getGoodsList()
          }
        }
      })
    },
    // 获取一级分类
    getCate () {
      function fliterItem (item) {
        if (!item) return null
        item.id = item.categoryId
        item.orgName = item.categoryName
        if (item.subCategoryList && item.subCategoryList.length) {
          item.childList = item.subCategoryList.map(ele => {
            let newImte = fliterItem(ele)
            return newImte
          })
        }
        return item
      }
      shopCategoryList({
        merchantId: this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.classifyList = (res.data.data.categories || []).map(item => {
            let newImte = fliterItem(item)
            return newImte
          })
        }
      })
    },
    // 排序
    sortTable (column) {
      this.loading = true
      this.tableData = []
      let dataParmas = {
        merchantId: this.$store.state.user.merchantId,
        offset: (this.pageObj.pageIndex - 1) * this.pageObj.pageSize,
        limit: this.pageObj.pageSize,
        goodsKind: this.searchObj.type,
        goodsStatus: 1,
        sortBy: column.order
      }
      if (!this.searchObj.type) {
        delete dataParmas.goodsKind
      }
      if (this.typeList.length > 0) {
        if (this.typeCode) {
          goodsList({
            ...dataParmas,
            goodsKind: this.typeCode
          }).then(res => {
            this.loading = false
            if (res.data.status === 200) {
              this.tableData = res.data.data.goods || []
              this.pageObj.total = res.data.data.total || 0
            }
          })
        } else {
          goodsList({
            ...dataParmas
          }).then(res => {
            this.loading = false
            if (res.data.status === 200) {
              this.tableData = res.data.data.goods || []
              this.pageObj.total = res.data.data.total || 0
            }
          })
        }
      } else {
        this.$Message.error(`你没有相关权限`)
      }
    },
    reset () {
      this.searchObj = {
        skuName: '',
        classify: null,
        classify2: '',
        type: ''
      }
      this.classifyList2 = []
      this.seleted()
    },
    skipAdd () {
      localStorage.removeItem('creatidt')
      this.$router.push({ name: 'commodity_create' })
    },
    skipDetail (row) {
      this.$router.push({ name: 'commodity_detail', params: { id: row.skuId } })
    },
    skipLog (row) {
      this.$router.push({ name: 'commodity_log', query: { id: row.skuId } })
    },
    skipEdit (row) {
      localStorage.removeItem('creatidt')
      this.$router.push({ name: 'commodity_edit', params: { id: row.skuId } })
    },
    freeze (row) {
      this.modalShow = true
      this.clickRow = row
    },
    sureFreeze () {
      this.modalShow = false
      freezeGoods({
        merchantId: this.merchantId,
        skuId: this.clickRow.skuId,
        updater: this.userId,
        updaterName: this.userName
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          if (this.typeList.length > 0) {
            this.getGoodsList()
          } else {
            this.$Message.error(`你没有相关权限`)
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    cancel () {
      this.modalShow = false
    },
    sureCover (row) {
      localStorage.removeItem('creatidt')
      this.$router.push({ name: 'commodity_edit', params: { id: row.skuId }, query: { copyids: 1 } })
      // this.clickRow = row
      // copyGoods({
      //   merchantId: this.merchantId,
      //   skuId: row.skuId,
      //   creator: this.userId,
      //   creatorName: this.userName
      // }).then(res => {
      //   const result = res.data || {}
      //   if (result.status === 200) {
      //     this.getGoodsList()
      //   } else {
      //     this.$Message.error(`${result.error}`)
      //   }
      // }).catch(err => {
      //   this.$Message.error(`${err}`)
      // })
    },
    changePageIndex (pageIndex) {
      this.pageObj.pageIndex = pageIndex
      this.getGoodsList()
    },
    changePageSize (pageSize) {
      this.pageObj.pageSize = pageSize
      this.seleted()
    }
  }
}
</script>
